package com.nine.mymall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nine.common.utils.PageUtils;
import com.nine.common.utils.Query;
import com.nine.common.utils.R;
import com.nine.common.vo.SkuHasStockVo;
import com.nine.mymall.ware.dao.WareSkuDao;
import com.nine.mymall.ware.entity.WareSkuEntity;
import com.nine.mymall.ware.fegin.ProductFeginService;
import com.nine.mymall.ware.service.WareSkuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeginService productFeginService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /**
         * skuId:
         * wareId:
         */

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("sku_id", skuId).eq("ware_id", wareId);
        List<WareSkuEntity> skuEntities = wareSkuDao.selectList(wrapper);

        if (skuEntities == null || skuEntities.size() == 0) {
            WareSkuEntity entity = new WareSkuEntity();
            entity.setSkuId(skuId);
            entity.setWareId(wareId);
            entity.setStock(skuNum);

            // TODO 远程查询 sku 名称，如果失败，事务无需回滚
            // 1、使用try catch 处理异常，不回滚
            // 2、还可以使用什么方法呢
            try {
                R info = productFeginService.info(skuId);
                Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if(info.getCode() == 0){
                    entity.setSkuName((String) skuInfo.get("skuName"));
                }
            }catch (Exception e){
                log.error("远程查询sku名称失败。。。");
            }

            entity.setStockLocked(0);
            wareSkuDao.insert(entity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    /**
     * 检查商品的库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> vos = new ArrayList<>();
        try {
            // 检索库存完成后的数据
            vos = skuIds.stream().map(skuId -> {
                SkuHasStockVo vo = new SkuHasStockVo();

                // 查询当前sku的总库存量：select sum(stock-stock_locked) from wms_ware_sku where sku_id = ?;
                Long count = baseMapper.getSkuStock(skuId);
                if(count == null){
                    count = 0L;
                }
                vo.setSkuId(skuId);
                vo.setHasStock(count > 0);

                return vo;
            }).collect(Collectors.toList());
        }catch (Exception e){
            e.printStackTrace();
        }
        return vos;
    }

}